<template>
  <el-card
    class="change-password-card"
    style="
      max-width: 600px;
      margin: 0 auto;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    "
  >
    <template #header>
      <div
        style="
          text-align: center;
          font-size: 24px;
          font-weight: 600;
          color: #303133;
        "
      >
        修改密码
      </div>
    </template>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      style="padding: 20px 0"
    >
      <!-- 原密码 -->
      <el-form-item
        label="原密码"
        prop="oldPassword"
        style="margin-bottom: 24px"
      >
        <el-input
          v-model="formData.oldPassword"
          type="password"
          placeholder="请输入原密码"
          show-password
          clearable
        />
      </el-form-item>

      <!-- 新密码 -->
      <el-form-item
        label="新密码"
        prop="newPassword"
        style="margin-bottom: 24px"
      >
        <template #label>
          <span style="display: flex; align-items: center; gap: 6px">
            新密码
            <el-tooltip placement="top" :show-after="300" :hide-after="100">
              <template #content>
                <div class="password-requirements-tooltip">
                  <div
                    style="font-weight: 600; margin-bottom: 8px; color: #fff"
                  >
                    密码要求：
                  </div>
                  <div
                    v-for="req in passwordRequirements"
                    :key="req.text"
                    style="
                      display: flex;
                      align-items: center;
                      font-size: 12px;
                      margin-bottom: 4px;
                      gap: 6px;
                      color: #fff;
                    "
                  >
                    <span
                      style="font-weight: bold; width: 12px; text-align: center"
                      :style="{ color: req.check ? '#67c23a' : '#f56c6c' }"
                    >
                      {{ req.check ? '✓' : '×' }}
                    </span>
                    <span>{{ req.text }}</span>
                  </div>
                </div>
              </template>
              <el-icon
                style="color: #909399; cursor: help; font-size: 14px"
                :style="{ color: formData.newPassword ? '#409eff' : '#909399' }"
              >
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </span>
        </template>

        <el-input
          v-model="formData.newPassword"
          type="password"
          placeholder="请输入新密码"
          show-password
          clearable
        />

        <!-- 密码强度指示器 -->
        <div v-if="formData.newPassword" style="margin-top: 8px">
          <div style="width: 300px">
            <el-progress
              :percentage="passwordStrength.level"
              :color="passwordStrength.color"
              :show-text="false"
              :text-inside="true"
              :stroke-width="16"
              style="width: 100%"
            >
              {{ passwordStrength.text }}
            </el-progress>
          </div>
        </div>
      </el-form-item>

      <!-- 确认密码 -->
      <el-form-item
        label="确认新密码"
        prop="confirmPassword"
        style="margin-bottom: 24px"
      >
        <el-input
          v-model="formData.confirmPassword"
          type="password"
          placeholder="请输入确认新密码"
          show-password
          clearable
        />
      </el-form-item>

      <!-- 按钮组 -->
      <el-form-item
        style="text-align: center; margin-top: 30px; margin-bottom: 0"
      >
        <el-button
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          style="margin: 0 15px; min-width: 120px"
        >
          确认修改
        </el-button>
        <el-button
          @click="handleReset"
          style="margin: 0 15px; min-width: 120px"
        >
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage, ElProgress } from 'element-plus';
import { QuestionFilled } from '@element-plus/icons-vue';
import UserAPI from '@/api/admin/admin/user';
import { clone } from 'xe-utils';

// 表单数据
const formData = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

// 表单引用
const formRef = ref(null);
const loading = ref(false);

// 密码强度计算
const passwordStrength = computed(() => {
  const password = formData.newPassword;
  if (!password) return { level: 0, text: '', color: '#dcdfe6' };

  let score = 0;
  const checks = {
    length: password.length >= 8,
    lowercase: /[a-z]/.test(password),
    uppercase: /[A-Z]/.test(password),
    numbers: /\d/.test(password),
    symbols: /[!@#$%^&*(),.?":{}|<>]/.test(password),
  };

  score = Object.values(checks).filter(Boolean).length;

  if (score <= 2) return { level: 25, text: '弱', color: '#f56c6c' };
  if (score <= 3) return { level: 50, text: '中等', color: '#e6a23c' };
  if (score <= 4) return { level: 75, text: '强', color: '#67c23a' };
  return { level: 100, text: '很强', color: '#67c23a' };
});

// 密码要求列表
const passwordRequirements = computed(() => [
  { text: '至少8个字符', check: formData.newPassword.length >= 8 },
  { text: '包含小写字母', check: /[a-z]/.test(formData.newPassword) },
  { text: '包含大写字母', check: /[A-Z]/.test(formData.newPassword) },
  { text: '包含数字', check: /\d/.test(formData.newPassword) },
  {
    text: '包含特殊字符',
    check: /[!@#$%^&*(),.?":{}|<>]/.test(formData.newPassword),
  },
]);

// 验证规则
const rules = reactive({
  oldPassword: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入原密码'));
        } else if (value.length < 6) {
          callback(new Error('原密码长度不能少于6位'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  newPassword: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入新密码'));
        } else if (value.length < 6) {
          callback(new Error('新密码长度不能少于6位'));
        } else if (value === formData.oldPassword) {
          callback(new Error('新密码不能与原密码相同'));
          // } else if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(value)) {
          //   callback(new Error('密码必须包含大小写字母和数字'));
        } else {
          // 重新验证确认密码
          if (formData.confirmPassword) {
            formRef.value?.validateField('confirmPassword');
          }
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  confirmPassword: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请确认新密码'));
        } else if (value !== formData.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
});

// 提交表单
const handleSubmit = async () => {
  try {
    loading.value = true;
    const valid = await formRef.value?.validate();
    if (valid) {
      const oldPassword = clone(formData.oldPassword);
      const newPassword = clone(formData.newPassword);
      await UserAPI.changePassword({ oldPassword, newPassword });
      ElMessage.success('密码修改成功！');
      formRef.value?.resetFields();
    }
  } catch (error) {
    ElMessage.error('请检查表单输入');
  } finally {
    loading.value = false;
  }
};

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields();
};
</script>

<style scoped>
.change-password-card {
  border-radius: 12px;
}

.password-strength-container {
  animation: fadeIn 0.3s ease-in-out;
}

.password-requirements-tooltip {
  max-width: 250px;
  line-height: 1.4;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .change-password-card {
    margin: 20px;
    max-width: none;
  }

  :deep(.el-form--label-top .el-form-item__label) {
    padding-bottom: 8px;
  }
}
</style>
